import { createRouter, createWebHashHistory } from 'vue-router'
import generatedRoutes from 'virtual:generated-pages'
import { setupLayouts } from 'virtual:generated-layouts'
import NProgress from '@/utils/nprogress'
import { useGlobalStore } from '@/stores/modules/global'

const router = createRouter({
  history: createWebHashHistory(),
  routes: setupLayouts(generatedRoutes)
})

router.beforeEach(async (to, from, next) => {
  const globalStore = useGlobalStore()

  NProgress.start()

  if (to.path.toLocaleLowerCase() === '/login') {
    if (globalStore.token) return next(from.fullPath)
    return next()
  }

  if (!globalStore.token) return next({ path: '/login', replace: true })

  globalStore.setRoutePath(to.path)

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export default router
